#include "daemon_runner.h"
#include "daemon_process.h"
#include "thirdparty/log/log.h"
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <signal.h>
#include <assert.h>

#define DAEMON_COUNT 2

static DaemonProcess subprocesses[DAEMON_COUNT];
static int running = 1;

void daemon_signalHandler(int signal)
{
    assert(signal == SIGTERM);
    running = 0;
}

void daemon_runner_run()
{
    signal(SIGTERM, daemon_signalHandler);
    // 首先需要将进程变为守护进程
    if (daemon(0, 1) < 0)
    {
        log_error("Daemonize failed");
        exit(EXIT_FAILURE);
    }

    // 手动处理进程的标准输入和标准输出
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    open("/dev/null", O_RDWR);
    open(LOG_FILE, O_RDWR | O_CREAT, 0644);
    open(LOG_FILE, O_RDWR | O_CREAT, 0644);

    // 初始化子进程
    daemon_process_init(subprocesses, "app");
    daemon_process_init(subprocesses + 1, "ota");

    // 启动子进程，并定时检查子进程的状态
    while (running)
    {
        for (int i = 0; i < DAEMON_COUNT; i++)
        {
            daemon_process_start(subprocesses + i);
        }
        usleep(100000);
    }

    for (int i = 0; i < DAEMON_COUNT; i++)
    {
        daemon_process_stop(subprocesses + i);
        daemon_process_free(subprocesses + i);
    }
}